package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi-back/cache"
	"logi-back/models"
	"logi-back/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.User
	redis_key := "login_" + username
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	err := models.DB.Where("username=?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，禁止登录",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func CreateRoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	nid, _ := strconv.Atoi(c.Query("nid"))
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "关联成功",
		"data": data,
	})
	return
}
func QueryUserRole(c *gin.Context) {
	/*
		SELECT
		*
		FROM
		roles
		LEFT JOIN user_roles ON roles.id=user_roles.rid
	*/
	uid := c.Query("uid")
	var role models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id=user_roles.rid").
		Where("user_roles.uid=?", uid).Debug().First(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})
	return
}
func QueryRoleNode(c *gin.Context) {
	/*
		SELECT
		*
		FROM
		nodes
		LEFT JOIN role_nodes ON nodes.id=role_nodes.nid
	*/
	rid := c.Query("rid")
	var node models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id=role_nodes.nid").
		Where("role_nodes.rid=?", rid).Debug().First(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
	return
}
func CreatePerson(c *gin.Context) {
	per_name := c.PostForm("per_name")
	if per_name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Person{
		PerName: per_name,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func CreatePerOrder(c *gin.Context) {
	order_id, _ := strconv.Atoi(c.PostForm("order_id"))
	order_name := c.PostForm("order_name")
	area := c.PostForm("area")
	if order_id == 0 || order_name == "" || area == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.PerOrder{
		OrderId:   order_id,
		OrderName: order_name,
		Area:      area,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func ListPersonOrder(c *gin.Context) {
	/*
			SELECT
		  per_orders.order_id,
		  per_orders.order_name,
		  per_orders.area,
		  people.per_name,
		  per_orders.created_at
		FROM
		per_orders
		LEFT JOIN people ON people.id=per_orders.order_id

	*/
	var perOrder []models.PerOrderList
	redis_key := "list_person_order_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Debug().Table("per_orders").
			Select("per_orders.order_id,\n\t  per_orders.order_name,\n\t  per_orders.area,\n\t  people.per_name,\n\t  per_orders.created_at").
			Joins("LEFT JOIN people ON people.id=per_orders.order_id").
			Debug().Find(&perOrder)
		jsonData, _ := json.Marshal(&perOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &perOrder)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表成功",
		"data": perOrder,
	})
	return
}
func DetailPersonOrder(c *gin.Context) {
	/*
	   	SELECT
	        per_orders.order_id,
	        per_orders.order_name,
	        per_orders.area,
	        people.per_name,
	        per_orders.created_at
	      FROM
	      per_orders
	      LEFT JOIN people ON people.id=per_orders.order_id
	      WHERE
	        per_orders.order_id=1
	*/
	id := c.Query("id")
	var perOrder models.PerOrderList
	redis_key := "detail_person_order_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Debug().Table("per_orders").
			Select("per_orders.order_id,\n\t  per_orders.order_name,\n\t  per_orders.area,\n\t  people.per_name,\n\t  per_orders.created_at").
			Joins("LEFT JOIN people ON people.id=per_orders.order_id").
            Where("per_orders.order_id=?", id).
			Debug().Find(&perOrder)
		jsonData, _ := json.Marshal(&perOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &perOrder)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表成功",
		"data": perOrder,
	})
	return
}
